
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
from whiff import stream

example_table_json = """
{
"atts": ["name", "age", "phone"],
"data": [
{"name": "aaron", "age":5, "phone": 1111},
{"name": "betty", "age":15, "phone": 2111},
{"name": "cathy", "age":25, "phone": 3111}
]
}
"""
example_name = "betty"

class table(misc.utility):
    "format table from json representation"
    def __init__(self, namevariable="action", tablevariable="jsonData"):
        self.namevariable = namevariable
        self.tablevariable = tablevariable
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        tvariable = self.param_value(self.tablevariable, env)
        nvariable = self.param_value(self.namevariable, env)
        table_text = resolver.unquote(whiffenv.cgiGet(env, tvariable, example_table_json))
        table_json = self.param_json(table_text, env)
        #pr "table_json is", table_json
        name = whiffenv.cgiGet(env, nvariable, example_name)
        #pr "name is", name
        atts = table_json["atts"]
        data = table_json["data"]
        row = None
        newrow = True
        for r in data:
            rname = r["name"]
            if rname==name:
                row = r
                newrow = False
        #pr "row is", row
        D = {}
        D["name"] = name
        D["new"] = newrow
        D["age"] = row.get("age", "0")
        D["phone"] = row.get("phone", "xxx")
        result = form % D
        start_response("200 OK", [('Content-Type', "text/html")])
        ##pr "result=", repr(result)
        return [stream.mystr(result)]

form = """
<form>
<input id="oldname" type="hidden" name="oldname" value="%(name)s">
name: <input id="name" name="name" value="%(name)s"><br>
age: <input id="age" name="age" value="%(age)s"><br>
phone: <input id="phone" name="phone" value="%(phone)s"><br>
</form>
"""

__middleware__ = table
    
